//
//  SearchServerOneViewController.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/6/12.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "SearchServerOneViewController.h"
#import "TagView.h"
#import "SearchServerTableViewCell.h"
#import "SendServerDetailViewController.h"

@interface SearchServerOneViewController()<TagViewDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong)TagView * tagView; // 标签View
@property (nonatomic, strong) UISearchBar *searchBar; // 搜索View
@property (nonatomic, strong) UILabel *titleLabel; // （热门分类）
@property (nonatomic, strong) UITableView *mainTableView; // 主框架
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, strong) NSMutableArray *datamuArray;// 热门分类 数据源
@property (nonatomic, strong) NSMutableArray *thirdDatamuArray;// 手机维修 > 苹果手机 > 苹果手机 数据源
@property (nonatomic, strong) NSString *keyWords;// 关键词
@end

@implementation SearchServerOneViewController
/**
 获取热门类别接口
 */
- (void)gethotserviceList {
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=hotservicecat" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            //            ShowMessage(@"操作成功");
            NSArray *array = responseObject[@"data"];
            for (NSDictionary *dic in array) {
                [self.datamuArray addObject:dic[@"catname"]];
            }
            self.tagView.arr = self.datamuArray;
        }else{
            ShowMessage(@"操作失败");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 搜索服务类别接口
 */
- (void)getSearchInfoMationList {
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=searchservicecat" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"keywords":self.keyWords} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            //            ShowMessage(@"操作成功");
            self.thirdDatamuArray = responseObject[@"data"];
            [self.mainTableView reloadData];
        }else{
            ShowMessage(responseObject[@"message"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
- (void)viewDidLoad
{
    self.title = @"发布服务";
    [self.view addSubview:self.mainTableView];
    [self.view addSubview:self.tagView];
//    self.tagView.arr = @[@"锤子",@"见过",@"膜拜单车",@"微信支付",@"Q",@"王者荣耀",@"蓝淋网",@"阿珂",@"半生",@"猎场",@"QQ空间",@"王者荣耀助手",@"斯卡哈复健科",@"安抚",@"沙发上",@"日打的费",@"问问",@"无人区",@"阿斯废弃物人情味",@"沙发上",@"日打的费",@"问问",@"无人区",@"阿斯废弃物人情味",@"沙发上",@"日打的费",@"问问",@"无人区",@"阿斯废弃物人情味",@"沙发上",@"日打的费",@"问问",@"无人区",@"阿斯废弃物人情味"];
    [self gethotserviceList];
    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.titleLabel];
    self.mainTableView.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.thirdDatamuArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchServerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchServerTableViewCell class])];
    NSArray *array = self.thirdDatamuArray[indexPath.row];
    NSString *stra = array[0][@"cat_name"];
    NSString *strb = array[1][@"cat_name"];
    NSString *strc = array[2][@"cat_name"];
    cell.titleLabel.text = [NSString stringWithFormat:@"%@ > %@ > %@",stra,strb,strc];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.thirdDatamuArray[indexPath.row][2];
    
    SendServerDetailViewController *VC = [[SendServerDetailViewController alloc]init];
    VC.isChooseBigType = NO;
    VC.secondDataDic = dic;
    [self.navigationController pushViewController:VC animated:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50 / HEIGHT_6S_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor clearColor];
    
    UILabel *tsLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 / WIDTH_6S_SCALE, 0, SCREEN_WIDTH, 31 / HEIGHT_6S_SCALE)];
    tsLabel.backgroundColor = [UIColor clearColor];
    tsLabel.textColor = getColor(textColor);
    tsLabel.textAlignment = NSTextAlignmentLeft;
    tsLabel.font = DEF_FontSize_14;
    tsLabel.text = @"点击服务类别，立刻发布服务";
    [bgView addSubview:tsLabel];
    return bgView;
}
#pragma mark - CCTagViewDelegate
-(void)handleSelectTag:(NSString *)keyWord backindexid:(NSInteger)indextag
{
    NSLog(@"keyWord ---- %@--------id:%ld",keyWord,indextag);
    self.keyWords = keyWord;
    self.searchTextField.text = keyWord;
    self.mainTableView.hidden = NO;
    self.titleLabel.hidden = YES;
    self.tagView.hidden = YES;
    
    [self getSearchInfoMationList];
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar // 点击搜索按钮
{
    NSLog(@"SearchButton");
    [self performSelector:@selector(hideKeyboardWithSearchBar:) withObject:searchBar afterDelay:0];
    self.mainTableView.hidden = NO;
    self.titleLabel.hidden = YES;
    self.tagView.hidden = YES;
    
    self.keyWords = self.searchTextField.text;
    [self getSearchInfoMationList];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar //点击取消按钮
{
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText // 输入的 搜索内容
{
    NSString *inputStr = searchText;
    if (searchBar.text.length == 0) // 点击X 隐藏键盘 和tableview
    {
        [self performSelector:@selector(hideKeyboardWithSearchBar:) withObject:searchBar afterDelay:0];
        self.mainTableView.hidden = YES;
        self.titleLabel.hidden = NO;
        self.tagView.hidden = NO;
    }
}
- (void)hideKeyboardWithSearchBar:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}
-(UISearchBar *)searchBar{
    if(!_searchBar){
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10 / WIDTH_6S_SCALE, SafeAreaTopHeight + 20, SCREEN_WIDTH - 20 / WIDTH_6S_SCALE, 35 / HEIGHT_6S_SCALE)];
        _searchBar.placeholder = @"点击搜索，快速找到您的服务类别";
        _searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:_searchBar.bounds.size];
        //背景图片
        //    searchBar.backgroundImage = [UIImage imageNamed:@"clearImage"];
        _searchBar.delegate = self;
        //显示右侧取消按钮
        _searchBar.showsCancelButton = YES;
        //光标颜色
        _searchBar.tintColor = getColor(blueColor);
        //拿到searchBar的输入框
        UITextField *searchTextField = [_searchBar valueForKey:@"searchField"];
        searchTextField.font = DEF_FontSize_14;
        searchTextField.backgroundColor = getColor(bgColor);
        searchTextField.layer.cornerRadius = 18 / HEIGHT_6S_SCALE;
        searchTextField.layer.masksToBounds = YES;
        self.searchTextField = searchTextField;
        //拿到取消按钮
        UIButton *cancleBtn = [_searchBar valueForKey:@"cancelButton"];
        //设置按钮上的文字
        [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        //设置按钮上文字的颜色
        [cancleBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }
    return _searchBar;
}
- (TagView *)tagView{
    if (!_tagView) {
        _tagView = [[TagView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleLabel.frame) + 20 / HEIGHT_6S_SCALE, SCREEN_WIDTH, 0)];
        _tagView.backgroundColor = [UIColor clearColor];
        _tagView.delegate = self;
    }
    return _tagView;
}
/** 取消searchBar背景色 */
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.searchBar.frame.origin.x + 10 / WIDTH_6S_SCALE, CGRectGetMaxY(self.searchBar.frame) + 10 / HEIGHT_6S_SCALE, 200 / WIDTH_6S_SCALE, 20 / HEIGHT_6S_SCALE)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textColor = getColor(textColor);
        _titleLabel.font = DEF_FontSize_14;
        _titleLabel.text = @"热门类别";
    }
    return _titleLabel;
}
#pragma mark - init
- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchBar.frame) + 10 / HEIGHT_6S_SCALE, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _mainTableView.backgroundColor = getColor(whiteColor);
        _mainTableView.tableHeaderView = self.headerView;
        _mainTableView.tableFooterView = self.footerView;
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 动态行高
        _mainTableView.rowHeight = UITableViewAutomaticDimension;
        // 预估行高
        _mainTableView.estimatedRowHeight = 80;
        [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
        [_mainTableView registerClass:[SearchServerTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SearchServerTableViewCell class])];
    }
    return _mainTableView;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
        _headerView.backgroundColor = [UIColor grayColor];
    }
    return _headerView;
}
- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}
- (NSMutableArray *)datamuArray
{
    if (!_datamuArray) {
        _datamuArray = @[].mutableCopy;
    }
    return _datamuArray;
}
- (NSMutableArray *)thirdDatamuArray
{
    if (!_thirdDatamuArray) {
        _thirdDatamuArray = @[].mutableCopy;
    }
    return _thirdDatamuArray;
}
@end

